package com.mcp_life.module.userbasemodules.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mcp_life.entity.dto.ApplyStoreDTO;
import com.mcp_life.entity.dto.UserRegDTO;
import com.mcp_life.entity.pojo.*;
import com.mcp_life.common.context.UserContextHolder;
import com.mcp_life.common.exception.BusinessException;
import com.mcp_life.entity.apiResult.RealNameAuthResponse;
import com.mcp_life.entity.dto.UserRealNameDTO;
import com.mcp_life.entity.vo.UserVO;
import com.mcp_life.module.servicemodules.mapper.HomeServiceMapper;
import com.mcp_life.module.servicemodules.mapper.RestaurantMapper;
import com.mcp_life.module.servicemodules.mapper.SupermarketMapper;
import com.mcp_life.module.userbasemodules.mapper.UserMapper;
import com.mcp_life.module.userbasemodules.service.UserService;
import com.mcp_life.util.AliyunApiUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AliyunApiUtils aliyunApiUtils;
    @Autowired
    private HomeServiceMapper homeServiceMapper;
    @Autowired
    private SupermarketMapper supermarketMapper;
    @Autowired
    private RestaurantMapper restaurantMapper;
//    @Autowired
//    private aliApi aliApi;


    @Override
    public boolean authenticate(String account, String password) {
        User user = userMapper.findByAccount(account);
        if (user != null) {
            //TODO: 实际项目中应该使用BCryptPasswordEncoder等加密方式验证密码
            password= DigestUtils.md5DigestAsHex(password.getBytes());
            if (user.getPassword().equals(password)){
                log.info("用户验证成功{}", user);
                return true;
            }
            else
                throw new BusinessException(600,"密码错误");
        }
        else
            throw new BusinessException(601,"用户不存在");
        //找不到用户，或者密码错误都应该抛出异常
    }

    /**
     * 用户注册接口
     * @param registerDTO
     */
    @Override
    public void register(UserRegDTO registerDTO) {
        log.info("用户注册{}", registerDTO);
        //对密码进行MD5加密
        registerDTO.setPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes()));
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        User existUser = userMapper.findByAccount(registerDTO.getAccount());
        if (existUser != null){
            throw new BusinessException(602,"用户已存在");
        }
        if (registerDTO.getPassword() == null || registerDTO.getPassword().isEmpty()){
            throw new BusinessException(603,"密码不能为空");
        }
        //逻辑校验
        //校验规则：userid自动生成，账号不能重复，昵称初始默认，密码不为空，性别不能为空，角色初始默认为普通用户
        //初始实名认证为0，初始状态为1，生成账户号为userid+id;
        //生成userid:当前时间戳+随机数+用户账号
        user.setUserId(System.currentTimeMillis() + (int)(Math.random() * 1000) + registerDTO.getAccount());
        //默认初始昵称为nick+@+account
        user.setNickname("nick@"+user.getAccount());
        //默认性别为男
        //todo: 初始可以默认一个头像，用户后期可以更改
        user.setAvatar("image_url");//默认头像
        //初始默认未实名
        user.setIsRealName(0);
        //默认角色为普通用户
        user.setRole(0);
        //创建时间
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        //默认状态
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        user.setStatus(1);
        log.info("用户注册成功{}", user);
        userMapper.insert(user);


    }
    @Override

    public boolean realNameRegister(String userId, String idCard, String name) {
        log.info("用户实名注册，用户ID: {}, 身份证: {}, 姓名: {}", userId, idCard, name);

        // 参数验证
        if (StringUtils.isEmpty(userId)) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (StringUtils.isEmpty(idCard)) {
            throw new IllegalArgumentException("身份证号不能为空");
        }
        if (StringUtils.isEmpty(name)) {
            throw new IllegalArgumentException("姓名不能为空");
        }

        // 验证身份证格式
//        if (!isValidIdCard(idCard)) {
//            throw new IllegalArgumentException("身份证号格式不正确");
//        }

        try {
            log.info("调用阿里云实名认证API，参数: name={}, id_number={}", name, idCard);

            // 调用阿里云API（使用Body参数）
            String result = aliyunApiUtils.verifyIdentity(idCard, name);

            log.info("阿里云实名认证API返回结果: {}", result);

            // 解析API响应结果
            if (result != null && !result.isEmpty()) {
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode jsonNode = objectMapper.readTree(result);

                    // 根据阿里云API文档检查认证结果
                    String code = jsonNode.has("code") ? jsonNode.get("code").asText() : "";
                    boolean isSuccess = "200".equals(code);

                    if (isSuccess) {
                        // 认证成功，更新用户状态
                       // updateUserRealNameStatus(userId, idCard, name);
                        return true;
                    } else {
                        String message = jsonNode.has("message") ? jsonNode.get("message").asText() : "认证失败";
                        log.warn("实名认证失败，API返回: {}", result);
                        throw new RuntimeException("实名认证失败: " + message);
                    }
                } catch (Exception e) {
                    log.error("解析阿里云API响应失败: {}", result, e);
                    throw new RuntimeException("实名认证响应解析失败: " + e.getMessage());
                }
            }

            log.warn("阿里云API返回空响应");
            return false;

        } catch (Exception e) {
            log.error("实名认证失败，userId: {}, idCard: {}, name: {}", userId, idCard, name, e);
            throw new RuntimeException("实名认证失败: " + e.getMessage());
        }
    }

    /**
     * 加入家政商家
     * @param applyStoreDTO
     */
    @Override
    public void applyHomeServiceStore(ApplyStoreDTO applyStoreDTO) {
        HomeServiceStore homeServiceStore = applyStoreDTO.getHomeServiceStore();
        log.info("用户加入家政商家{}", homeServiceStore);
        homeServiceStore.setUserId(UserContextHolder.getUserId());
        homeServiceStore.setCreatedTime(new Timestamp(System.currentTimeMillis()));
        homeServiceStore.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        homeServiceMapper.insert(homeServiceStore);

    }

    /**
     * 加入超市商家
     * @param applyStoreDTO
     */
    @Override
    public void applySuppermarketStore(ApplyStoreDTO applyStoreDTO) {
        SupermarketStore supermarketStore = applyStoreDTO.getSupermarketStore();
        log.info("用户加入超市商家{}", supermarketStore);
        supermarketStore.setUserId(UserContextHolder.getUserId());
        supermarketStore.setCreatedTime(new Timestamp(System.currentTimeMillis()));
        supermarketStore.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        supermarketStore.setIsDeliveryAccept(0);//默认不接受成为快递代收站点
        supermarketMapper.insert(supermarketStore);
    }

    /**
     * 加入餐厅商家
     * @param applyStoreDTO
     */
    @Override
    public void applyRestaurantStore(ApplyStoreDTO applyStoreDTO) {
       RestaurantStore restaurantStore = applyStoreDTO.getRestaurantStore();
       log.info("用户加入餐厅商家{}", restaurantStore);
       restaurantStore.setUserId(UserContextHolder.getUserId());
       restaurantStore.setCreatedTime(new Timestamp(System.currentTimeMillis()));
       restaurantStore.setUpdateTime(new Timestamp(System.currentTimeMillis()));
       restaurantMapper.insert(restaurantStore);
    }

    @Override
    public UserVO getUserInfo(String userId) {
        return userMapper.getUserInfoByUserId(userId);
    }

    @Override
    public void update(User user) {
         userMapper.update(user);
    }

}
